package com.fh.common.distributedlock;

import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.Collections;

/**
 * @author qiujunda
 * @date 2019年2月14日
 * @description
 */
//@Component
public class JedisLockTool {

    @Autowired
    private JedisPoolUtil jedisPoolUtil;

    private final String LOCK_SUCCESS = "OK";
    private final String SET_IF_NOT_EXIST = "NX";
    private final String SET_WITH_EXPIRE_TIME = "PX";
    //最大超时时间10秒
    private final int MAX_TIME_OUT = 10000;
    //获取分布式主键尝试次数默认10次
    private final int RETRY_TIMES = 10;

    /**
     * 尝试获取分布式锁
     *
     * @param lockKey    锁
     * @param requestId  请求标识
     * @param expireTime 超期时间 毫秒，最大10秒 10000,防止获取锁后进程异常终止
     * @return 是否获取成功
     */
    public boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) {
        if (expireTime > MAX_TIME_OUT) {
            expireTime = MAX_TIME_OUT;
        }
        Jedis jedis = jedisPoolUtil.getJedis();
        boolean getKey = false;
        for (int i = 0; i < RETRY_TIMES; i++) {
            SetParams setParams = new SetParams();
            setParams.ex(expireTime);
            setParams.nx();
            String result = jedis.set(lockKey, requestId, setParams);
//    		String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
            getKey = LOCK_SUCCESS.equals(result) ? true : false;
            if (getKey) {
                break;
            }
        }
        jedisPoolUtil.reset(jedis);

        return getKey;
    }

    public boolean tryGetDistributedLock(String lockKey, String requestId) {
        return tryGetDistributedLock(lockKey, requestId, MAX_TIME_OUT);
    }


    private final Long RELEASE_SUCCESS = 1L;

    /**
     * 释放分布式锁
     *
     * @param lockKey   锁
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public boolean releaseDistributedLock(String lockKey, String requestId) {
        Jedis jedis = jedisPoolUtil.getJedis();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        jedisPoolUtil.reset(jedis);
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }

}
